
import { Layout, Menu,Image } from 'antd';
import { useSelector} from 'react-redux';
import Logo from '@/logo.jpeg'
import menus from '@/router/menus'
import {useState} from 'react'
import {useNavigate,useLocation} from 'react-router-dom'
import { useEffect } from 'react';
import {
  getCheckedKeysArr,
  getPermissionMenus
} from '@/utils/permissionMenus'
const { Sider } = Layout;
const rootSubmenuKeys = []
menus.forEach(item=>{
  item.children && rootSubmenuKeys.push(item.key)
})
export default function SideBar() {

  // 写个函数，当浏览器刷新的时候，默认的二级菜单会打开
  // ['/pro','/pro/list']
  const {pathname} = useLocation()
  const getSubMenu = pathname => {
    const pathArray = pathname.split('/').slice(1)
    const result = pathArray.reduce((newArr,item,index)=>{
      const str = newArr[index] + '/' + item  //str = ''+'/'+'pro' = '/pro'   '/pro/list'  '/pro/list/home'
      newArr.push(str)   // newArr=['','/pro','/pro/list','/pro/list/home']
      return newArr
    },[''])
    return result
  }

  const collapsed = useSelector(state=>state.app.collapsed)
  const [openKeys, setOpenKeys] = useState(getSubMenu(pathname));
  const navigate = useNavigate()
  const onOpenChange = (keys)=>{
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys); // 打开深层次的菜单 openKeys=['/pro','/pro/list']
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  }
  const handleClick = ({ key })=>{
    navigate(key)
    setSelectedKeys([key]) // 点击菜单项的时候，也需要设置selectedKeys数组
  }
  const [selectedKeys,setSelectedKeys] = useState([pathname])

  // 监听pathname的变化，如果路径改变了，需要设置seelctedKey,openkeys
  useEffect(()=>{
    setSelectedKeys([pathname])
    setOpenKeys(getSubMenu(pathname))
  },[pathname])


  // 左侧导航权限实现
  const checkedKeys = useSelector(state=>state.admin.checkedKeys)
  const adminname = useSelector(state=>state.admin.adminname)
  let newMenus = []
  if(checkedKeys.length === 0 && adminname === 'admin'){ // 如果是超级管理员，直接给所有查询权限的方式
    newMenus = menus
  }else{
    // 获取所有的keys数组
    const newCheckedKeys = getCheckedKeysArr(checkedKeys)
    // 从menus导航中根据keys数组进行筛选导航
    newMenus = getPermissionMenus(menus,newCheckedKeys)
  }

  return (
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="logo" style={{
          display:'flex',
          justifyContent:'center',
          alignItems:'center',
          color:'#fff'
        }}>
          <Image src={Logo} width='28px' height='28px'/>&nbsp;
          {
            !collapsed && <div style={{height:'32px',lineHeight:'32px',overflow:'hidden'}}>嗨购后台管理系统</div>
          }
        </div>
        <Menu
          theme="dark"
          mode="inline"
          items={newMenus} 
          openKeys={openKeys}
          onOpenChange={onOpenChange}
          onClick={handleClick}
          selectedKeys={selectedKeys}
        />
      </Sider>
  )
}
